package com.sinodata.bsm.cicp.collector.sqlserver;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.AbstractJDBCCollector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.DBConnectionUtil;
import com.sinodata.bsm.common.vo.ResPropertyValue;

public class IOAndNet extends AbstractJDBCCollector {
    private static final Logger logger = Logger.getLogger(IOAndNet.class);

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        try {
            String[] propMetas = getPropMeta();
            String serverName = this.getParamMap().get("ServerName");

            String sql = "sp_monitor";
            String[] rs = this.getStrings(serverName, sql, ip);

            ResPropertyValue propertyValueX = new ResPropertyValue();
            ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
            for (int i = 0; i < propMetas.length; i++) {
                propValues[i] = ResPropertyValue.createPropValue(rs[i], propMetas[i]);
            }

            propertyValueX.setValues(propValues);
            values.add(propertyValueX);
        } catch (Exception e) {
            logger.error("failed to collect sqlserver IOAndNet", e);
            throw new CollectorException(e);
        }
        return values;
    }

    private String[] getStrings(String serverName, String sql, String ip) throws CollectorException {
        String[] propValArr = new String[7];

        CallableStatement cstmt = null;
        ResultSet rst = null;
        Connection conn = null;
        try {
            conn = DBConnectionUtil.getInstance().getConnection("sqlserver", ip, serverName);
            if (conn == null) {
                return null;
            }
            cstmt = conn.prepareCall(sql);
            cstmt.setQueryTimeout(10);
            cstmt.execute();
            cstmt.getMoreResults();
            cstmt.getMoreResults();
            rst = cstmt.getResultSet();
            String packetsReceived = null;
            String packetsSent = null;
            String packetsErrors = null;
            if (rst != null) {
                while (rst.next()) {
                    packetsReceived = rst.getString(1);
                    packetsReceived = packetsReceived.substring(0, packetsReceived.indexOf("("));
                    packetsSent = rst.getString(2);
                    packetsSent = packetsSent.substring(0, packetsSent.indexOf("("));
                    packetsErrors = rst.getString(3);
                    packetsErrors = packetsErrors.substring(0, packetsErrors.indexOf("("));
                }
            }
            cstmt.getMoreResults();
            rst = cstmt.getResultSet();
            String totalRead = null;
            String totalWrite = null;
            String totalErrors = null;
            String connTimes = null;
            if (rst != null) {
                while (rst.next()) {
                    totalRead = rst.getString(1);
                    totalRead = totalRead.substring(0, totalRead.indexOf("("));
                    totalWrite = rst.getString(2);
                    totalWrite = totalWrite.substring(0, totalWrite.indexOf("("));
                    totalErrors = rst.getString(3);
                    totalErrors = totalErrors.substring(0, totalErrors.indexOf("("));
                    connTimes = rst.getString(4);
                    connTimes = connTimes.substring(0, connTimes.indexOf("("));
                }
            }

            propValArr[0] = "" + packetsReceived;
            propValArr[1] = "" + packetsSent;
            propValArr[2] = "" + packetsErrors;
            propValArr[3] = "" + connTimes;
            propValArr[4] = "" + totalRead;
            propValArr[5] = "" + totalWrite;
            propValArr[6] = "" + totalErrors;
        } catch (SQLException sqle) {
            logger.error("Collecting sqlserver IO and Net information", sqle);
            throw new CollectorException(sqle);

        } catch (IOException ioex) {
            logger.error("Collecting sqlserver IO and Net information", ioex);
            throw new CollectorException(ioex);

        } finally {
            try {
                if (rst != null)
                    rst.close();
                if (cstmt != null)
                    cstmt.close();
            } catch (SQLException e) {
            }
            DBConnectionUtil.getInstance().returnConnection(conn);
        }
        return propValArr;
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "SeverName" };
    }

    @Override
    public String[] getPropMeta() {
        return new String[] { "NetworkRecievingPackets", "NetworkSendingPackets", "NetworkErrTimes", "LoginOrTryTimes", "PhysicalReadTimes", "PhysicalWriteTimes", "PhysicalErrTimes" };
    }

}
